package cn.lg.soar.core.util;

import java.io.*;

/**
 * 基于 fastjson 的序列化器
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public interface SerializeUtils {

    /**
     * 序列化
     * @param o
     * @return
     */
    static byte[] serialize(Object o) {
        try (
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bos)
        ) {
            oos.writeObject(o);
            return bos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 反序列化
     * @param serialize
     * @return
     */
    static Object deserialize(byte[] bytes) {
        try (
                ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bis)
        ) {
            return ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 复制对象
     * @param o
     * @return
     */
    static Object clone(Object o) {
        byte[] serialize = serialize(o);
        return deserialize(serialize);
    }
}
